<?php
// 加载通用文件
require_once __DIR__ . '/../common/autoload.php';

// 检查是否已安装
if (!file_exists(__DIR__ . '/../.installed')) {
    json_response(['success' => false, 'message' => '系统未安装'], 503);
}

// 确保会话已启动
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

// 设置CORS头
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

// 处理OPTIONS请求
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    header('HTTP/1.1 200 OK');
    exit;
}

// 设置调试模式
$debug_mode = true;

// 获取会话ID
$session_id = session_id();

// 如果是POST请求，从JSON请求体中获取数据
$data = [];
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $json_data = file_get_contents('php://input');
    $data = json_decode($json_data, true) ?: [];
}

// 处理不同的操作
$action = isset($data['action']) ? $data['action'] : (isset($_GET['action']) ? $_GET['action'] : '');

try {
    switch ($action) {
        case 'create':
            // 创建订单
            if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
                json_response(['success' => false, 'message' => '请求方法不正确'], 405);
            }
            createOrder($session_id, $data);
            break;
        case 'detail':
            // 获取订单详情
            if (!isset($_GET['order_id'])) {
                json_response(['success' => false, 'message' => '缺少订单ID'], 400);
            }
            getOrderDetail($session_id, $_GET['order_id']);
            break;
        default:
            json_response(['success' => false, 'message' => '未知操作'], 400);
            break;
    }
} catch (Exception $e) {
    // 记录错误
    error_log("Order API Error: " . $e->getMessage());
    // 返回错误响应
    json_response(['success' => false, 'message' => '系统错误: ' . $e->getMessage()], 500);
}

/**
 * 检查用户是否已登录
 * @return bool
 */
function isLoggedIn() {
    if (session_status() === PHP_SESSION_NONE) {
        session_start();
    }
    
    return isset($_SESSION['user_id']);
}

/**
 * 创建订单
 * @param string $session_id 会话ID
 * @param array $data 请求数据
 */
function createOrder($session_id, $data) {
    global $debug_mode;
    
    try {
        // 开始事务
        Database::beginTransaction();
        
        // 验证参数
        if (!isset($data['payment_method'])) {
            Database::rollBack();
            json_response(['success' => false, 'message' => '缺少支付方式'], 400);
        }
        
        // 获取当前会员
        $member = isLoggedIn() ? current_user() : null;
        if (!$member) {
            Database::rollBack();
            json_response(['success' => false, 'message' => '请先登录'], 401);
        }
        
        $member_id = $member['id'];
        $payment_method = $data['payment_method'];
        $remark = isset($data['remark']) ? $data['remark'] : '';
        
        if ($debug_mode) {
            error_log("创建订单 - 会员ID: {$member_id}, 支付方式: {$payment_method}");
        }
        
        // 获取购物车商品
        $cart_items = Database::fetchAll(
            "SELECT c.*, p.name as product_name, p.price, p.points_reward 
            FROM cart_items c 
            JOIN products p ON c.product_id = p.id 
            WHERE c.session_id = ?",
            [$session_id]
        );
        
        if (empty($cart_items)) {
            Database::rollBack();
            json_response(['success' => false, 'message' => '购物车为空'], 400);
        }
        
        // 计算订单总额和积分奖励
        $total_amount = 0;
        $total_points_reward = 0;
        
        foreach ($cart_items as $item) {
            $item_total = $item['price'] * $item['quantity'];
            $total_amount += $item_total;
            
            // 计算积分奖励（如果商品有积分奖励）
            if (!empty($item['points_reward'])) {
                $total_points_reward += $item['points_reward'] * $item['quantity'];
            }
        }
        
        // 检查余额支付
        if ($payment_method === 'balance') {
            if ($member['balance'] < $total_amount) {
                Database::rollBack();
                json_response(['success' => false, 'message' => '余额不足，请充值后再购买'], 400);
            }
            
            // 扣除会员余额
            $new_balance = $member['balance'] - $total_amount;
            Database::update('members', ['balance' => $new_balance], 'id = ?', [$member_id]);
            
            if ($debug_mode) {
                error_log("订单余额支付 - 扣除前余额: {$member['balance']}, 扣除后余额: {$new_balance}");
            }
        }
        
        // 生成订单编号和取餐号
        $order_no = 'ORD' . date('YmdHis') . rand(1000, 9999);
        $queue_number = getNextQueueNumber();
        
        // 创建订单
        $order_id = Database::insert('orders', [
            'member_id' => $member_id,
            'order_no' => $order_no,
            'queue_number' => $queue_number,
            'total_amount' => $total_amount,
            'payment_method' => $payment_method,
            'payment_status' => $payment_method === 'balance' ? 'paid' : 'pending',
            'order_status' => 'pending',
            'remark' => $remark,
            'created_at' => date('Y-m-d H:i:s')
        ]);
        
        // 添加订单明细
        foreach ($cart_items as $item) {
            Database::insert('order_items', [
                'order_id' => $order_id,
                'product_id' => $item['product_id'],
                'quantity' => $item['quantity'],
                'price' => $item['price'],
                'subtotal' => $item['price'] * $item['quantity']
            ]);
        }
        
        // 添加积分记录（如果有积分奖励）
        if ($total_points_reward > 0) {
            $new_points = $member['points'] + $total_points_reward;
            
            // 更新会员积分
            Database::update('members', ['points' => $new_points], 'id = ?', [$member_id]);
            
            // 记录积分变动
            Database::insert('points_log', [
                'member_id' => $member_id,
                'points' => $total_points_reward,
                'action' => 'order_reward',
                'reference_id' => $order_id,
                'description' => "订单 {$order_no} 消费奖励",
                'created_at' => date('Y-m-d H:i:s')
            ]);
            
            if ($debug_mode) {
                error_log("订单积分奖励 - 原有积分: {$member['points']}, 新增积分: {$total_points_reward}, 现有积分: {$new_points}");
            }
        }
        
        // 清空购物车
        Database::delete('cart_items', 'session_id = ?', [$session_id]);
        
        // 提交事务
        Database::commit();
        
        // 返回成功响应
        json_response([
            'success' => true,
            'message' => '订单创建成功',
            'order' => [
                'id' => $order_id,
                'order_no' => $order_no,
                'queue_number' => $queue_number,
                'total_amount' => $total_amount,
                'points_reward' => $total_points_reward
            ]
        ]);
    } catch (Exception $e) {
        // 回滚事务
        Database::rollBack();
        
        error_log("Create Order Error: " . $e->getMessage());
        json_response(['success' => false, 'message' => '创建订单失败: ' . $e->getMessage()], 500);
    }
}

/**
 * 获取下一个取餐号
 * @return string 取餐号
 */
function getNextQueueNumber() {
    // 获取今天已分配的最大取餐号
    $today = date('Y-m-d');
    $today_start = $today . ' 00:00:00';
    $today_end = $today . ' 23:59:59';
    
    $last_number = Database::fetchColumn(
        "SELECT queue_number FROM orders 
        WHERE created_at BETWEEN ? AND ? 
        ORDER BY id DESC LIMIT 1", 
        [$today_start, $today_end]
    );
    
    // 如果今天还没有订单，从1开始
    if (!$last_number) {
        return '001';
    }
    
    // 取餐号+1
    $next_number = intval($last_number) + 1;
    
    // 格式化为3位数
    return str_pad($next_number, 3, '0', STR_PAD_LEFT);
}

/**
 * 获取订单详情
 * @param string $session_id 会话ID
 * @param int $order_id 订单ID
 */
function getOrderDetail($session_id, $order_id) {
    // 记录请求信息
    error_log("Order Detail Request - order_id: $order_id, session_id: $session_id");
    
    // 获取当前会员
    $member = isLoggedIn() ? current_user() : null;
    if (!$member) {
        error_log("Order Detail Error - 用户未登录");
        json_response(['success' => false, 'message' => '请先登录'], 401);
    }

    error_log("Order Detail - 用户ID: " . $member['id'] . ", 用户名: " . $member['username']);

    // 查询订单信息
    $order = Database::fetch("SELECT * FROM orders WHERE id = ? AND user_id = ?", [$order_id, $member['id']]);
    
    if (!$order) {
        error_log("Order Detail Error - 订单不存在或无权查看: order_id=$order_id, user_id=" . $member['id']);
        json_response(['success' => false, 'message' => '订单不存在或无权查看'], 404);
    }
    
    error_log("Order Detail - 订单信息获取成功: order_id=$order_id");
    
    // 查询订单商品 - order_items表中已包含product_name字段
    $order_items = Database::fetchAll("SELECT * FROM order_items WHERE order_id = ?", [$order_id]);
    
    error_log("Order Detail - 订单商品获取成功: " . count($order_items) . " 个商品");
    
    json_response([
        'success' => true,
        'order' => $order,
        'items' => $order_items
    ]);
} 